package com.jake.data_structure_learning.hash.set;

public class MyHashSet {
    private Integer size;
    private Object[] obj;

    public MyHashSet() {
        size = 16;
        obj = new Object[size];
    }

    public void add(int key) {
        if (this.contains(key)) {
            return;
        }
        int index = this.getHashIndex(key);
        Object object = obj[index];
        if (object == null) {
            int[] newArr = new int[1];
            newArr[0] = key;
            obj[index] = newArr;
        } else {
            int[] arr = (int[]) object;
            int[] newArr = new int[arr.length + 1];
            for (int i = 0; i < arr.length; i++) {
                newArr[i] = arr[i];
            }
            newArr[arr.length] = key;
            obj[index] = newArr;
        }
    }

    public void remove(int key) {
        int index = this.getHashIndex(key);
        Object object = obj[index];
        if (object == null) {
            return;
        } else {
            int[] arr = (int[]) object;
            int slow = 0;
            for (int fast = 0; fast < arr.length; fast++) {
                if (arr[fast] != key) {
                    arr[slow] = arr[fast];
                    slow++;
                }
            }
            if (slow == 0) {
                obj[index] = null;
            } else if (slow < arr.length) {
                int[] newArr = new int[slow];
                for (int i = 0; i < slow; i++) {
                    newArr[i] = arr[i];
                }
                obj[index] = newArr;
            }
        }
    }

    /**
     * Returns true if this set contains the specified element
     */
    public boolean contains(int key) {
        for (int i = 0; i < obj.length; i++) {
            if (obj[i] == null) {
                continue;
            } else {
                int[] arr = (int[]) obj[i];
                for (int j = 0; j < arr.length; j++) {
                    if (arr[j] == key) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private int getHashIndex(int key) {
        return key % size;
    }
}
